
/******************************************************************************
*@file  : app.c
*@brief : application
******************************************************************************/

#include "app.h" 


#define TIM_CLOCK_FREQ            (8000000U)  // TIMER INTERNAL CLK = 8MHz 
#define TIM_PWM_OUTPUT_FREQ       (100000U)   // PWM output frequency = 100KHz

TIM_HandleTypeDef TIM_Handler;     


/******************************************************************************
*@brief:  Initialize the selected TIMx.
*@param:  None
*@return: None
******************************************************************************/
void TIMx_Init(void)  
{    
	TIM_OC_InitTypeDef Tim_OC_Init_Para;  
    GPIO_InitTypeDef TIM_GPIO_Init;    
    uint32_t timer_clock;
    
    __HAL_RCC_GPIOB_CLK_ENABLE();
    

    timer_clock = HAL_RCC_GetPCLK1Freq();
    
    
    if (HAL_RCC_GetHCLKFreq() != timer_clock)  // if hclk/pclk != 1, then TIMx clk = pclk * 2  
    {
        timer_clock =  timer_clock << 1;    
    }
	
	TIM_Handler.Instance = TIM15;
	TIM_Handler.Init.ARRPreLoadEn = TIM_ARR_PRELOAD_ENABLE;        
	TIM_Handler.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; 
	TIM_Handler.Init.CounterMode = TIM_COUNTERMODE_UP; 
	TIM_Handler.Init.RepetitionCounter = 0;  
	TIM_Handler.Init.Prescaler = (timer_clock/TIM_CLOCK_FREQ) - 1; 
	if (timer_clock%TIM_CLOCK_FREQ > TIM_CLOCK_FREQ/2) 
	{
		TIM_Handler.Init.Prescaler = TIM_Handler.Init.Prescaler + 1;  
	}
	TIM_Handler.Init.Period = (TIM_CLOCK_FREQ/TIM_PWM_OUTPUT_FREQ) - 1;  // period = 10us, 100KHz        
	
	HAL_TIMER_MSP_Init(&TIM_Handler);       
	HAL_TIMER_Base_Init(&TIM_Handler);  
	
	Tim_OC_Init_Para.OCMode = OUTPUT_MODE_PWM1;  
	Tim_OC_Init_Para.OCIdleState = OUTPUT_IDLE_STATE_0;
	Tim_OC_Init_Para.OCNIdleState = OUTPUT_IDLE_STATE_0;      
	Tim_OC_Init_Para.OCPolarity = OUTPUT_POL_ACTIVE_HIGH;  
	Tim_OC_Init_Para.OCNPolarity = OUTPUT_POL_ACTIVE_HIGH;    
	Tim_OC_Init_Para.OCFastMode =  OUTPUT_FAST_MODE_DISABLE;  
	Tim_OC_Init_Para.Pulse = (TIM_Handler.Init.Period + 1)/2;// 50% duty cycle 

	HAL_TIMER_Output_Config(TIM_Handler.Instance, &Tim_OC_Init_Para, TIM_CHANNEL_1);    
    
    TIM_GPIO_Init.Mode = GPIO_MODE_AF_PP;          
    TIM_GPIO_Init.Pull = GPIO_NOPULL;    
    TIM_GPIO_Init.Alternate = GPIO_FUNCTION_2;
    TIM_GPIO_Init.Drive = GPIO_DRIVE_LEVEL3;     
    TIM_GPIO_Init.Pin = GPIO_PIN_2;//TIM15 CH1-PB2-AF2
    HAL_GPIO_Init(GPIOB, &TIM_GPIO_Init);   
    printfS("TIM15 CH1-PB2-AF2\r\n");               
}

/******************************************************************************
*@brief:  APP_Test  
*@param:  None
*@return: None
******************************************************************************/
void APP_Test(void)  
{ 
    printfS("Timer15 Channel_1 outputs a PWM waveform with a frequency of 100KHZ\r\n"); 
    
	TIMx_Init();
    
	HAL_TIM_PWM_Output_Start(TIM_Handler.Instance, TIM_CHANNEL_1);  
    
	while(1)
	{
 
 
	}
}
